---
title: Testing Considerations
description: Testing considerations for IdleTimer
---

In order to write tests that include IdleTimer, a few things will need to be mocked.
Examples will be provided for the [jest](https://jestjs.io/) framework
and the [testing-library](https://testing-library.com/docs/react-testing-library/intro) 
utilities, but the principles can be applied to any framework.

To keep your tests clean and modular, you will want to create a startup script 
and add it to the `setupFilesAfterEnv` section of your `jest.config.js` or `package.json`. 
We will assume the setup file is called `test.setup.js` for the following implementation.

### Mock Timers
If you are using worker thread timers, you can mock them for your testing
environment. IdleTimer exposes a function to do this for you.

In your `test.setup.js`, add the following:

```js
import { createMocks } from 'react-idle-timer'
beforeAll(createMocks)
```

This will have jest or your test runner of choice use the main thread timers
for testing.

### Mock MessageChannel
IdleTimer uses [MessageChannel](https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel)
for the cross tab messaging layer internally. This is not mocked by default
in `js-dom`. If you are using the cross tab feature, you will need to mock the global.
Add the following to your `test.setup.js`.

```js
import { MessageChannel } from 'worker_threads'
import { cleanup } from '@testing-library/react'

beforeAll(() => {
  // @ts-ignore
  global.MessageChannel = MessageChannel
})

afterAll(cleanup)
```

If you are using Typescript you will have to either ignore the global assignment
or extend the global name space for your test runner. Since you are unlikely to 
need types for MessageChannel, `// @ts-ignore` will suffice.

### Full Mock

Here is the full mock requirements to test with IdleTimer.

```js
//
// jest.config.js
//

export default {
  ...otherOptions,
  setupFilesAfterEnv: [
    './test.setup.js'
  ]
}
```

```js
//
// test.setup.js
//

import { createMocks } from 'react-idle-timer'
import { MessageChannel } from 'worker_threads'
import { cleanup } from '@testing-library/react'

beforeAll(() => {
  createMocks()
  global.MessageChannel = MessageChannel
})

afterAll(cleanup)
```

<Divider mt={6} />

With this setup script, you will be able to fully test your application
with IdleTimer. If you need more examples, you can check out the 
[test suite](https://github.com/supremetechnopriest/react-idle-timer/tree/master/tests) 
for IdleTimer itself.
